package com.relife.sys.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.relife.common.http.BrowserType;
import com.relife.common.http.BrowserUtils;
import com.relife.common.http.HttpUtil;
import com.relife.common.model.AjaxJson;
import com.relife.common.model.Client;
import com.relife.common.model.ClientManager;
import com.relife.common.model.Page;
import com.relife.common.utils.StringUtil;
import com.relife.common.utils.SysConfig;
import com.relife.core.easyui.Easyui;
import com.relife.core.entity.DepartmentEntity;
import com.relife.core.entity.FunctionEntity;
import com.relife.core.entity.LogEntity;
import com.relife.core.service.LogService;
import com.relife.sys.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


/**
 * @author WU
 * @date 2015-4-3 上午12:00:05
 */
@Controller
@RequestMapping("sys/admin")
public class AdminController extends BaseController {
	@Autowired
	private AdminService adminService;
	@Autowired
	private LogService logServiceI;

	/**
	 * 用户登录
	 * 
	 * @author WU
	 * @date 2015-5-26 下午10:20:58
	 * @return
	 */
	@ResponseBody
	@RequestMapping("login")
	@SuppressWarnings("unchecked")
	public AjaxJson Login(HttpServletRequest req, String icode) {
		AjaxJson j = new AjaxJson();
		try {
			String code = (String) req.getSession().getAttribute(SysConfig.CAPTCHA_SESSION_KEY);
			if (StringUtil.isEmpty(icode) || StringUtil.isEmpty(code)) {
				j.setSuccess(false);
				j.setMsg("验证码不能为空！");
				return j;
			}
			if (!code.toUpperCase().equals(icode.toUpperCase())) {
				j.setSuccess(false);
				j.setMsg("验证码错误！");
				return j;
			}

			String userName = req.getParameter("un");
			String pwd = req.getParameter("pwd");
			if (StringUtil.isEmpty(userName) || StringUtil.isEmpty(pwd)) {
				j.setSuccess(false);
				j.setMsg("帐号或密码不能为空！");
				return j;
			}

			Client client = new Client();

			adminService.login(userName, pwd, client);

			BrowserType type = BrowserUtils.getBrowserType(req);
			client.setBrowser(type == null ? null : type.toString());
			client.setIp(HttpUtil.getIpAddr(req));
			client.setLoginTime(new Date());
			client.setTheme(HttpUtil.getCookie("theme"));
			j.setObj(client.getDepartSize());
			ClientManager.getInstance().addClinet(client);
			@SuppressWarnings("rawtypes")
			Map map = new HashMap();
			map.put("name", client.getUser().getName());
			map.put("callNo", client.getUser().getCallNo());
			map.put("userName", client.getUser().getUserName());
			j.setAttributes(map);
			if (client.getDepartSize() == 1) {
				client.setDepart(client.getDepartList().get(0));

				LogEntity log = new LogEntity();
				log.setOptType(0);
				logServiceI.optLog(log);
			} else {
				List<DepartmentEntity> deplist = client.getDepartList();
				JSONArray array = new JSONArray();
				for (int i = 0; i < deplist.size(); i++) {
					JSONObject dep = new JSONObject();
					dep.put("id", deplist.get(i).getId());
					if (deplist.get(i).getParent() != null) {
						dep.put("depName", deplist.get(i).getParent().getName() + ">>" + deplist.get(i).getName());
					} else {
						dep.put("depName", deplist.get(i).getName());
					}
					array.add(dep);
				}
				map.put("deplist", array);
				j.setAttributes(map);
			}

		} catch (Exception e) {
			j.setException(e);
			e.printStackTrace();
		}
		log.info("[" + req.getRemoteAddr() + "]" + j.getMsg());
		return j;
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年4月25日 下午5:22:47
	 * @return
	 */
	@ResponseBody
	@RequestMapping("setDepart")
	public AjaxJson setDepart(String departId) {
		AjaxJson j = new AjaxJson();
		Client client = ClientManager.getInstance().getClientSession();
		for (int i = 0; i < client.getDepartList().size(); i++) {
			if (client.getDepartList().get(i).getId().equals(departId)) {
				client.setDepart(client.getDepartList().get(i));
				break;
			}
		}
		adminService.getClient(client);
		LogEntity log = new LogEntity();
		log.setOptType(0);
		logServiceI.optLog(log);

		return j;
	}

	/**
	 * 主页
	 * 
	 * @author WU
	 * @date 2015-5-26 下午10:20:40
	 * @return
	 */
	@RequestMapping("home")
	public String home(HttpServletRequest request) {
		Client client = ClientManager.getInstance().getClientSession();
		request.setAttribute("menu", client);
		return "home";
	}

	/**
	 * 客户端获取菜单信息
	 * 
	 * @author WU
	 * @date 2016年5月10日 上午10:57:10
	 * @param parentId
	 * @param res
	 */
	@RequestMapping
	public void getMenu(String parentId, HttpServletResponse res) {
		Client client = ClientManager.getInstance().getClientSession();
		List<FunctionEntity> list = new ArrayList<FunctionEntity>();
		for (FunctionEntity fun : client.getfList()) {
			if (StringUtil.isEmpty(parentId)) {
				if (fun.getParent() == null) {
					list.add(fun);
				}
			} else {
				if (fun.getParent() != null && parentId.equals(fun.getParent().getId())) {
					list.add(fun);
				}
			}
		}

		for (int i = 0; i < list.size(); i++) {
			for (FunctionEntity fun : client.getfList()) {
				if (fun.getParent() != null && fun.getParent().getId().equals(list.get(i).getId())) {
					list.add(fun);
				}
			}
		}
		Page p = new Page();
		p.setList(list);
		p.setFields("id,parent.id,name,url,orderBy");
		Easyui.ztree(p, res, false);
	}

	/**
	 * 注销用户
	 * 
	 * @author WU
	 * @date 2015-6-20 上午2:49:58
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/logOut")
	public AjaxJson logOut() {
		AjaxJson j = new AjaxJson();
		try {
			ClientManager.getInstance().removeClinet();
		} catch (Exception e) {
			e.printStackTrace();
			j.setException(e);
		}
		return j;
	}

	/**
	 * 桌面注销用户
	 */
	@ResponseBody
	@RequestMapping
	public String desktopOut(HttpServletRequest request) {
		try {
			String sid = request.getParameter("sid");
			ClientManager.getSession(sid).invalidate();
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return "";
	}

	/**
	 * 桌面首页
	 * 
	 * @author zou
	 * @return
	 */
	@RequestMapping
	public String desktop() {
		return "desktop";
	}

	/**
	 * 定期和服务器会话
	 */
	@ResponseBody
	@RequestMapping
	public String keepLive() {
		return "ok";
	}

	/**
	 * 
	 * @author WU
	 * @date 2015年12月24日 下午10:00:45
	 * @return
	 */
	@RequestMapping("/editPwd")
	public String editPwd() {
		return "sys/user/editPwd";
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年7月12日 下午4:26:10
	 * @return
	 */
	@RequestMapping
	public String editPassword() {
		return "sys/user/editPassword";
	}

	/**
	 * 
	 * @author WU
	 * @date 2015年12月24日 下午10:29:52
	 * @param oldPwd
	 * @param pwd
	 * @param newPwd
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updatePwd")
	public AjaxJson updatePwd(String oldPwd, String pwd, String newPwd) {
		AjaxJson j = new AjaxJson();
		try {
			adminService.updatePwd(oldPwd, pwd, newPwd);
			j.setMsg("密码修改成功，下次登录时候开始生效。");
		} catch (Exception e) {
			e.printStackTrace();
			j.setException(e);
		}
		return j;
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年5月30日 下午4:39:37
	 * @return
	 */
	@RequestMapping
	public String theme(HttpServletRequest req) {
		Client client = ClientManager.getInstance().getClientSession();
		req.setAttribute("theme", client.getTheme());
		return "sys/theme";
	}

	/**
	 * 
	 * @author WU
	 * @date 2016年5月30日 下午4:39:32
	 * @param theme
	 * @return
	 */
	@ResponseBody
	@RequestMapping
	public AjaxJson setTheme(String theme, HttpServletResponse res) {
		AjaxJson j = new AjaxJson();
		try {
			Client client = ClientManager.getInstance().getClientSession();
			client.setTheme(theme);
			Cookie cookie = new Cookie("theme", theme);
			cookie.setMaxAge(60 * 60 * 24 * 7);
			res.addCookie(cookie);

		} catch (Exception e) {
			e.printStackTrace();
			j.setException(e);
		}
		return j;
	}

}
